package com.gupaoedu.chat.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.concurrent.EventExecutorGroup;
import org.msgpack.MessagePack;

import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by ASUS on 2017/10/21.
 * 自定义IM协议的编码器
 */
public class IMDecoder extends ByteToMessageDecoder {
    //协议定义
    private Pattern pattern = Pattern.compile("^\\[(.*)\\](\\s\\-\\s(.*))?");

    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        System.out.println("IMDecoder decode....");
        try {
            //现获取可读的字节数
            final int length=byteBuf.readableBytes();
            final byte[] array=new byte[length];
            //内容
            String content = new String(array, byteBuf.readerIndex(), length);
            System.out.println("IMDecoder decode....content:"+content);
            //空消息不断
            if (!(null == content || "".equals(content.trim()))) {
                if (!IMP.isIMP(content)) {
                    channelHandlerContext.channel().pipeline().remove(this);
                    return;
                }
            }

            //从byteBuffer中获取对应的字节数组
            byteBuf.getBytes(byteBuf.readerIndex(),array,0,length);
            //添加到集合中
            list.add(new MessagePack().read(array,IMMessage.class));
            //集合数据清空!
            byteBuf.clear();
        } catch (IOException e) {
            e.printStackTrace();
            channelHandlerContext.channel().pipeline().remove(this);
        }
    }


    /**
     * 将字符串 解码成对应的对象
     * @param msg
     * @return
     */
    public IMMessage decode(String msg) {
        if(null ==msg || "".equals(msg.trim())){
            return null;
        }
        try {
            Matcher matcher=pattern.matcher(msg);
            String header="";
            String content="";
            if(matcher.matches()){
                //如果内容满足条件
                header= matcher.group(1);
                content=matcher.group(3);
            }

            //头部消息 字符串数组
            String[] heads=header.split("\\]\\[");
            long time=0;
            try {
                time=Long.parseLong(heads[1]);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            String nickName=heads[2];
            nickName=nickName.length()<10?nickName:nickName.substring(0,9);

            if(msg.startsWith("["+IMP.LOGIN.getName()+"]")){
                return  new IMMessage(heads[0],time,nickName);
            }else if(msg.startsWith("["+IMP.CHAT.getName()+"]")){
                return  new IMMessage(heads[0],time,nickName,content);
            }else if(msg.startsWith("["+IMP.FLOWER.getName()+"]")){
                return new IMMessage(heads[0],time,nickName);
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
